#!/bin/bash

# SmartInput 管理后台启动脚本
# 单独启动管理后台应用

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ADMIN_DIR="$PROJECT_ROOT/admin-panel"

# PID文件路径
PIDS_DIR="$PROJECT_ROOT/.pids"
ADMIN_PID_FILE="$PIDS_DIR/admin.pid"

# 日志文件路径
LOGS_DIR="$PROJECT_ROOT/logs"
ADMIN_LOG="$LOGS_DIR/admin.log"

# 创建必要的目录
mkdir -p "$PIDS_DIR" "$LOGS_DIR"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        return 0  # 端口被占用
    else
        return 1  # 端口空闲
    fi
}

# 等待端口启动
wait_for_port() {
    local port=$1
    local service_name=$2
    local max_attempts=30
    local attempt=0
    
    print_message $YELLOW "等待 $service_name 启动 (端口 $port)..."
    
    while [ $attempt -lt $max_attempts ]; do
        if check_port $port; then
            print_message $GREEN "✅ $service_name 已启动 (端口 $port)"
            return 0
        fi
        sleep 1
        attempt=$((attempt + 1))
        echo -n "."
    done
    
    print_message $RED "❌ $service_name 启动超时"
    return 1
}

# 主函数
main() {
    print_message $GREEN "🛠️  SmartInput 管理后台启动脚本"
    print_message $BLUE "================================"
    
    # 检查管理后台目录
    if [ ! -d "$ADMIN_DIR" ]; then
        print_message $RED "❌ 管理后台目录不存在: $ADMIN_DIR"
        exit 1
    fi
    
    # 检查是否已经在运行
    if [ -f "$ADMIN_PID_FILE" ] && kill -0 $(cat "$ADMIN_PID_FILE") 2>/dev/null; then
        print_message $YELLOW "⚠️  管理后台应用已在运行 (PID: $(cat $ADMIN_PID_FILE))"
        print_message $BLUE "   📍 地址: https://localhost:3002"
        return 0
    fi
    
    # 检查端口3002是否被占用
    if check_port 3002; then
        print_message $YELLOW "⚠️  端口3002已被占用，尝试停止现有进程..."
        pkill -f "vite.*admin-panel" || true
        sleep 2
    fi
    
    # 进入管理后台目录
    cd "$ADMIN_DIR"
    
    # 检查依赖
    if [ ! -d "node_modules" ]; then
        print_message $YELLOW "📦 安装管理后台依赖..."
        npm install
    fi
    
    # 启动管理后台应用
    print_message $BLUE "🚀 启动管理后台应用..."
    nohup npm run dev > "$ADMIN_LOG" 2>&1 &
    local admin_pid=$!
    echo $admin_pid > "$ADMIN_PID_FILE"
    
    # 等待管理后台应用启动
    if wait_for_port 3002 "管理后台应用"; then
        print_message $GREEN "✅ 管理后台应用启动成功 (PID: $admin_pid)"
        print_message $BLUE "   📍 地址: https://localhost:3002"
        print_message $BLUE "   📄 日志: $ADMIN_LOG"
        
        # 自动打开浏览器
        if command -v open >/dev/null 2>&1; then
            print_message $YELLOW "🌐 正在打开浏览器..."
            open "https://localhost:3002"
        elif command -v xdg-open >/dev/null 2>&1; then
            print_message $YELLOW "🌐 正在打开浏览器..."
            xdg-open "https://localhost:3002"
        fi
    else
        print_message $RED "❌ 管理后台应用启动失败"
        exit 1
    fi
    
    print_message $BLUE "================================"
    print_message $GREEN "🎉 管理后台启动完成！"
    print_message $BLUE ""
    print_message $BLUE "🛠️  管理命令:"
    print_message $BLUE "   停止管理后台: pkill -f 'vite.*admin-panel'"
    print_message $BLUE "   查看状态: ./status.sh"
    print_message $BLUE "   查看日志: tail -f $ADMIN_LOG"
}

# 执行主函数
main "$@" 